﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.IO;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Windows;
using XYAC.Framework.MonitorTireMaterialOnline.Extensions;
using System.Collections.ObjectModel;
using Microsoft.VisualBasic;
using System.Data;
using XYAC.Framework.MonitorTireMaterialOnline.Context;

namespace XYAC.Framework.MonitorTireMaterialOnline.ViewModels
{
    /// <summary>
    /// 系统配置
    /// </summary>
    public partial class SystemConfigViewModel_o : ViewModelBase
    {

        public SystemConfigViewModel_o(IOptionsMonitor<AppConfig> options, ILogger<SystemConfigViewModel> logger, IServiceProvider provider)
        {
            this.AppConfig = options;
            this.Logger = logger;
            this.Provider = provider;
            //this.Folder1Path = this.AppConfig.CurrentValue.Folder1Path;
            //this.Folder2Path = this.AppConfig.CurrentValue.Folder2Path;
            //this.Folder3Path = this.AppConfig.CurrentValue.Folder3Path;
            this.DetectionMachineNo = this.AppConfig.CurrentValue.DetectionMachineNo;
            this.DataCleanerDaysInterval = this.AppConfig.CurrentValue.DataCleanerDaysInterval + "";
            this.MachineType = this.AppConfig.CurrentValue.MachineType + "";
            this.OracleMesConnectionString = this.AppConfig.CurrentValue.OracleMesConnectionString;
            string[] strings = OracleMesConnectionString.Split(";");
            this.OracleDsn = strings[0].Split("=")[1];
            this.OracleAccName = strings[2].Split("=")[1];
            this.OraclePwd = strings[3].Split("=")[1];

            this.AccessCAreaHisConnectionString = this.AppConfig.CurrentValue.AccessCAreaHisConnectionString;
            strings = AccessCAreaHisConnectionString.Split(";");
            //"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\7号机\\Database\\HisData\\{DateNow}.mdb",
            this.Folder1Path = strings[1].Split("=")[1];
    


            _machineTypeList = new ObservableCollection<Item>();

            MachineTypeList.Add(new Item
            {
                Caption = "胎面",
                Value = "1"
            });
            MachineTypeList.Add(new Item
            {
                Caption = "胎侧",
                Value = "2"
            });
            MachineTypeList.Add(new Item
            {
                Caption = "三角胶",
                Value = "3"
            });
        }

        public Item CurrentItem(string idx)
        {
            foreach (var ss in MachineTypeList)
            {
                if (ss.Value.Equals(idx))
                    return ss;
            }
            return null;
        }

        public IOptionsMonitor<AppConfig> AppConfig { get; }
        public ILogger Logger { get; }
        public IServiceProvider Provider { get; }


        /// <summary>
        /// 自动启动状态
        /// </summary>
        [ObservableProperty]
        private Boolean _chkAutoStartIsChecked = AutoStartupHelper.IsAutoStartupEnabled();

        [ObservableProperty]
        private string _folder1Path;
        [ObservableProperty]
        private string _folder2Path;

        [ObservableProperty]
        private string _folder3Path;

        [ObservableProperty]
        private string _detectionMachineNo;
        [ObservableProperty]
        private string _oracleMesConnectionString;
        [ObservableProperty]
        private string _accessCAreaHisConnectionString;
        [ObservableProperty]
        private string _accessCAreaHisName;

        [ObservableProperty]
        private string _oracleDsnDbname;

        [ObservableProperty]
        private string _oracleDsn;
        [ObservableProperty]
        private string _oracleAccName;
        [ObservableProperty]
        private string _oraclePwd;

        [ObservableProperty]
        private string _dataCleanerDaysInterval;
        [ObservableProperty]
        private string _machineType;
        [ObservableProperty]
        private ObservableCollection<Item> _machineTypeList;
        /// <summary>
        /// 用户点击修改自动启动行为
        /// </summary>
        [RelayCommand]
        public void UserChangedAppStartupSet()
        {
            if (!this.ChkAutoStartIsChecked)
            {
                AdminHelper.EnsureAdmin();
                // 当复选框被选中时，取消自动启动
                AutoStartupHelper.SetAutoStartup(false);
            }
            else
            {
                //自我提权
                AdminHelper.EnsureAdmin();
                // 当复选框未选中时，启用自动启动
                AutoStartupHelper.SetAutoStartup(true);
            }
        }

        //[RelayCommand]
        //private void ShowEqpsManager()
        //{
        //    try
        //    {
        //        //测试三角胶弹窗
        //        //var view = this.Provider.GetService<SemiSteelTriangleRubberView>();
        //        //view.ClearViewModelValue();
        //        //var Window = new Window();
        //        //Window.Content = view;
        //        //Window.WindowState = WindowState.Maximized;
        //        //var result = Window.ShowDialog();

        //        var eqpsManager = this.Provider.GetService<Views.EquipmentMapping>();
        //        eqpsManager.WindowState = WindowState.Maximized;
        //        eqpsManager.Show();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("打开设备管理失败:" + ex.Message);
        //    }
        //}

        [RelayCommand]
        private void Save()
        {
            string tempStr = "DATA SOURCE=" + OracleDsn + ";PERSIST SECURITY INFO=True";
            tempStr = tempStr + ";USER ID=" + OracleAccName;
            tempStr = tempStr + ";PASSWORD=" + OraclePwd;
            OracleMesConnectionString = tempStr;
            this.AppConfig.CurrentValue.OracleMesConnectionString = this.OracleMesConnectionString;
            this.AppConfig.CurrentValue.MachineType = int.Parse(this.MachineType);
            this.AppConfig.CurrentValue.DataCleanerDaysInterval = int.Parse(this.DataCleanerDaysInterval);
            this.AppConfig.CurrentValue.DetectionMachineNo=this.DetectionMachineNo;

            tempStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Folder1Path;// this.AccessCAreaHisName+"\\{DateNow}.mdb";
            this.AccessCAreaHisConnectionString= tempStr;
            this.AppConfig.CurrentValue.AccessCAreaHisConnectionString = this.AccessCAreaHisConnectionString;

            //"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\7号机\\Database\\HisData\\{DateNow}.mdb",

            SaveNewJsonConfig();
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="floderType"></param>
        [RelayCommand]
        private void ChoiceFloder()
        {
            try
            {
                var tempFolder = FolderSelector.SelectFolder();
                if (tempFolder != null)
                {
                    this.Folder1Path = tempFolder + "\\{DateNow}.mdb";
                    //this.Folder1Path = tempFolder;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择目标文件夹失败:{ex.Message}");
            }
        }
        private void SaveNewJsonConfig()
        {
            try
            {
                const string configPath = "./Configs/";
                const string configFileName = "AppConfig.json";
                const string tempFileName = "AppConfig_temp.json";

                string configFullPath = Path.Combine(configPath, configFileName);
                string tempFullPath = Path.Combine(configPath, tempFileName);

                // 复制原始配置文件到临时文件
                File.Copy(configFullPath, tempFullPath, overwrite: true);
                var currentValue = this.AppConfig.CurrentValue.Clone();
                // 修改临时文件
                JsonObject appSetting;
                using (FileStream fs = new FileStream(tempFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    appSetting = JsonNode.Parse(fs).AsObject();

                    // 将当前的 CurrentAppConfig 序列化为 JsonNode
                    JsonNode sourceJsonNode = JsonSerializer.SerializeToNode(currentValue);

                    // 替换 "AppConfig" 节点
                    appSetting["AppConfig"] = sourceJsonNode;

                    // 清空文件并重置位置
                    fs.SetLength(0);
                    fs.Position = 0;

                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true // 格式化输出
                    };
                    JsonSerializer.Serialize(fs, appSetting, options);
                }

                // 原子性地替换原始配置文件
                File.Replace(tempFullPath, configFullPath, null);
                MessageBox.Show("保存成功！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存配置文件失败！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                this.Logger.LogError("保存配置文件失败", ex);
            }
        }
    }
}
